package com.httpapi;

import android.content.Context;
import android.util.Log;

import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

/**
 * okhttp3忽略证书验证
 */
public class SSLSocketClient {

//    /**
//     * app带证书验证的方法,使用是修改一下zhaoapi_server.cer即可,其他都是固定的模式,直接拷贝
//     */
//    public OkHttpClient setCard(String zhenshu) {
//        Context context = MainApp.getInstance();
//        zhenshu="oa.cer";
//        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        try {
//            //https固定模式,X.509是固定的模式
//            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
//            //关联证书的对象
//            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
//            keyStore.load(null);
//            String certificateAlias = Integer.toString(0);
//            //核心逻辑,信任什么证书,从Assets读取拷贝进去的证书
//            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(context.getAssets().open(zhenshu)));
//            SSLContext sslContext = SSLContext.getInstance("TLS");
//            //信任关联器
//            final TrustManagerFactory trustManagerFactory =
//                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//            //初始化证书对象
//            trustManagerFactory.init(keyStore);
//            sslContext.init
//                    (
//                            null,
//                            trustManagerFactory.getTrustManagers(),
//                            new SecureRandom()
//                    );
//            builder.sslSocketFactory(sslContext.getSocketFactory());
//            builder.addInterceptor(new LogInterceptor());
//            builder.hostnameVerifier(new HostnameVerifier() {
//                @Override
//                public boolean verify(String s, SSLSession sslSession) {
//                    return true;
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return builder.build();
//    }

    //获取这个SSLSocketFactory
    public static SSLSocketFactory getSSLSocketFactory(Context context) {
//        String zhenshu="oa.cer";
        try {

            //https固定模式,X.509是固定的模式
//            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            //关联证书的对象
//            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
//            keyStore.load(null);
//            String certificateAlias = Integer.toString(0);
            //核心逻辑,信任什么证书,从Assets读取拷贝进去的证书   root1 ---root2---oa
//            keyStore.setCertificateEntry(certificateAlias,
//                    certificateFactory.generateCertificate(context.getAssets().open(zhenshu)));
            SSLContext sslContext = SSLContext.getInstance("TLS");
//            //信任关联器
//            final TrustManagerFactory trustManagerFactory =
//                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//            //初始化证书对象
//            trustManagerFactory.init(keyStore);

//            SSLContext sslContext = SSLContext.getInstance("SSL");
//            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
            //信任所有证书
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //获取TrustManager
    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }

    //获取HostnameVerifier
    public static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
//                long creationTime = sslSession.getCreationTime();
//                try {
//                    Certificate[] peerCertificates = sslSession.getPeerCertificates();
//                    Certificate peerCertificate = peerCertificates[0];
//                    if(null != peerCertificate){
//                        (OpenSSLX509Certificate)peerCertificate.getPublicKey()
//                    }
//                } catch (SSLPeerUnverifiedException e) {
//                    e.printStackTrace();
//                }
//                SSLSessionContext sessionContext = sslSession.getSessionContext();
//                Enumeration<byte[]> ids = sessionContext.getIds();

                Log.d(SSLSocketClient.class.getSimpleName(),"验证主机："+s);
                Log.d(SSLSocketClient.class.getSimpleName(),"验证主机："+sslSession.getCipherSuite());
                Log.d(SSLSocketClient.class.getSimpleName(),"验证主机："+sslSession.getProtocol());
                Log.d(SSLSocketClient.class.getSimpleName(),"验证主机："+sslSession.isValid() );
                return sslSession.isValid();
            }
        };
        return hostnameVerifier;
    }
}
